package com.live.stamp.web.message.baseDataService.service;

import com.hikeSoft.common.utils.BaseUtils;
import com.live.stamp.base.service.impl.BaseSupportServiceImpl;
import com.live.stamp.global.commonenum.MessageTypeEnum;
import com.live.stamp.web.message.baseDataService.MessageBaseService;
import com.live.stamp.web.message.model.TMessage;
import com.live.stamp.web.message.vo.TMessageVo;
import org.springframework.boot.container.core.common.BusinessException;
import org.springframework.boot.container.core.log.ZKLogger;
import org.springframework.boot.container.core.log.ZKLoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cwd E-mail: wendong.cao@jsxfedu.com
 * @version 1
 * @date 2018/5/12 15:57
 */
@Service
public class MessageBaseServiceImpl extends BaseSupportServiceImpl implements MessageBaseService {
    private static final ZKLogger logger = ZKLoggerFactory.getLogger(MessageBaseServiceImpl.class);

    @Override
    public void addMessage(TMessage tMessage) throws BusinessException {
        logger.debug("enter method addMessage, param tMessage:{}", tMessage);

        try {
            this.getDao().insert(tMessage);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);

            throw new BusinessException("发送消息失败，" + e.getMessage());
        }
    }

    @Override
    public List<TMessage> messageList(TMessage tMessage) throws BusinessException {
        Map<String,Object> params = this.searchParma(tMessage);
        String sql = "select * from t_message m where 1=1 "+params.get("sql");

        try{
            return this.getDao().selectList(TMessage.class,sql,(Map<String, Object>) params.get("paramMap"));
        }catch(Exception e){
            logger.error(e.getMessage());
            throw new BusinessException(e.toString());
        }
    }

    @Override
    public List<TMessageVo> commonMessageList(TMessage tMessage) throws BusinessException {
        Map<String,Object> params = this.searchParma(tMessage);
        String sql = "select m.*,u.username as stampUserName, u.photoUrl as stampUserPhoto, i.tUserId as stampUserId, i.content as stampContent from t_message m, t_user u, t_inji_info i where m.busiId=i.id and u.id=i.tUserId and 1=1 "+params.get("sql") +" order by m.createTime desc";

        try{
            return this.getDao().selectList(TMessageVo.class,sql,(Map<String, Object>) params.get("paramMap"));
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            throw new BusinessException(e.toString());
        }
    }

    @Override
    public TMessage getOneMessage(TMessage tMessage) throws BusinessException {

        Map<String,Object> params = this.searchParma(tMessage);
        String sql = "select * from t_message m where 1=1 "+params.get("sql");

        try{
            return this.getDao().selectOne(TMessage.class,sql,(Map<String, Object>) params.get("paramMap"));
        }catch(Exception e){
            logger.error(e.getMessage());
            throw new BusinessException(e.toString());
        }
    }

    @Override
    public void updateMessage(TMessage tMessage) throws BusinessException {

        logger.debug("enter into updateMessage method. param tMessage:{}", tMessage);

        String sql = "UPDATE t_message SET $value$ WHERE ID =:id";
        Map<String, Object> params = new HashMap<>();
        params.put("id", tMessage.getId());

        String sqlValue = createUpdateParams(params, tMessage);
        sql = sql.replace("$value$", sqlValue);
        try {
            this.getDao().exec(sql, params);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException("更新失败");
        }
    }

    @Override
    public void updateAttenMessageRead(String userId) throws BusinessException {
        logger.debug("enter into updateAttenMessageRead method. param userId:{}", userId);

        String sql = "UPDATE t_message SET state='2' WHERE toUserId=:userId and state='1' and type='"+ MessageTypeEnum.ATTEN.name()+"'";
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);

        try {
            this.getDao().exec(sql, params);
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
            throw new BusinessException("更新失败");
        }
    }

    private Map<String,Object> searchParma(TMessage tMessage){
        if(tMessage == null){
            return Collections.emptyMap();
        }
        String sql = "";
        HashMap<String,Object> resMap = new  HashMap<String,Object>();
        HashMap<String,Object> paramMap = new  HashMap<String,Object>();
        if(BaseUtils.isNotBlank(tMessage.getId())){
            sql += " and m.id = :id";
            paramMap.put("id",tMessage.getId());
        }
        if(BaseUtils.isNotBlank(tMessage.getToUserId())){
            sql += " and m.toUserId = :toUserId";
            paramMap.put("toUserId",tMessage.getToUserId());
        }
        if(BaseUtils.isNotBlank(tMessage.getType())){
            sql += " and m.type = :type";
            paramMap.put("type",tMessage.getType());
        }
        if(BaseUtils.isNotBlank(tMessage.getState())){
            sql += " and m.state = :state";
            paramMap.put("state",tMessage.getState());
        }

        sql += " ";
        resMap.put("sql",sql);
        resMap.put("paramMap",paramMap);
        return resMap;
    }

    /**
     * 创建更新商品的信息
     * @param params 更新参数
     * @param tMessage 消息内容
     * @return 更新参数的sql
     */
    private String createUpdateParams(Map<String, Object> params, TMessage tMessage) {
        if(tMessage == null){
            logger.error("tMessage:{} not exist.");
            throw new BusinessException("消息不存在");
        }
        String sql = "";
        if(BaseUtils.isNotBlank(tMessage.getState())){
            sql += ", state = :state";
            params.put("state", tMessage.getState());
        }

        return sql.replaceFirst(",", "");
    }
}
